package com.chinaway.handler;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.jws.WebMethod;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chinaway.mobile.balance.impl.MobileBalanceSdImpl;
import com.chinaway.mobile.container.HttpDataContainer;
import com.chinaway.mobile.dao.SimDao;
import com.chinaway.mobile.model.Account;
import com.chinaway.mobile.model.CallbackBean;
import com.chinaway.mobile.model.MobileBean;
import com.chinaway.mobile.model.Sim;
import com.chinaway.mobile.validator.SDMobileValidator;
import com.chinaway.proxy.Proxy;
import com.chinaway.proxy.ProxyService;
import com.chinaway.router.Handler;
import com.chinaway.router.HandlerException;

public class MobileHandler implements Handler {
	private static final Log log = LogFactory.getLog(MobileHandler.class);
	private SimDao simDao;
	public final String MOBILEKEY = "sdmobile";
	private ProxyService proxyService;//key = shandongmobile
	private HttpDataContainer httpDataContainer;
	public SDMobileValidator sdvalidator=new SDMobileValidator();
	
	@WebMethod(exclude=true)
	public void setProxyService(ProxyService proxyService) {
		this.proxyService = proxyService;
		log.info("MobileHandler proxyService 初始化成功："+proxyService);
	}
	
	@WebMethod(exclude=true)
	public  void init(){
		this.proxyService.register(MOBILEKEY,sdvalidator);
		log.info("redis key:"+MOBILEKEY+" 注册成功！");
	}
	@WebMethod(exclude=true)
	public  Proxy getProxy(){
		Proxy proxy=null;
		do{
			proxy=proxyService.getProxy(MOBILEKEY);
		}while(proxy.getPort()>=8088);
		return proxy;
	}
	
	
	public void start_exec_tasksResult(){
		httpDataContainer.start_exec_tasksResult();
	}
	
	public String compute(Date from,Date to,int type){
		/*
		 * 校验请求参数
		 */
		if(type!=1&&type!=2&&type!=3 ){
			throw new HandlerException(40, "type不正确");
		}
		return httpDataContainer.Compute(from, to, type);
	}
	
	public  void register(String key){
		this.proxyService.register(key,sdvalidator);
		log.info("redis key:"+key+" 注册成功！");
	}
	
	// 回调PHP，更新数据,清空queueMap
	public  void sendBalance2PHP(){
		httpDataContainer.send();
	}
	
	/*
	 * 获取最新信息
	*/
	public Account onlyAccount(String mobile ,String password, String date, String city){
		/*
		 * 校验请求参数
		 */
		if( StringUtils.isBlank(mobile) ||StringUtils.isBlank(password) ||StringUtils.isBlank(String.valueOf(date))||StringUtils.isBlank(String.valueOf(city)) ){
			throw new HandlerException(40, "缺少必选参数");
		}
		Account account = null ;
		Proxy proxy=getProxy();
		if("sd".equals(city)){
			account=new MobileBalanceSdImpl(proxyService).onlyAccount(mobile, password, date, proxy);
		}
		return account ;
	}
	
	/*
	 * 获取最新信息
	*/
	public Account account(String mobile ,String password, String date, String city){
		/*
		 * 校验请求参数
		 */
		if( StringUtils.isBlank(mobile) ||StringUtils.isBlank(password) ||StringUtils.isBlank(String.valueOf(date))||StringUtils.isBlank(String.valueOf(city)) ){
			throw new HandlerException(40, "缺少必选参数");
		}
		Account account = null ;
		Proxy proxy=getProxy();
		if("sd".equals(city)){
			account=new MobileBalanceSdImpl(proxyService).account(mobile, password, date, proxy);
			if(account!=null){
				Sim sim = new Sim(account);
				simDao.update(sim);
			}
		}
		return account ;
	}
	
	/*
	 * 获取最新信息
	 * 参数：
	 * String list=[{'mobile':'123123','password':'12312','date':'1407',city:'sd'},.....]
	 *             [{"mobile":"14033100007","password":"1239","city":"sd","date":"201407"},{"mobile":"14033100008","password":"1240","city":"sd","date":"201407"}]
	 * String callbackurl={'app_url':'http://admin.gsp.cn/rest/',"app_key":'ips',"method":'gsp.sim_list.setSimBalance'}
	 * 					  {"app_url":"http://admin.gsp.cn/rest/","app_key":"ips","method":"gsp.sim_list.setSimBalance"}
	*/
	public String accounts(String list, String callbackurl){
		/*
		 * 校验请求参数
		 */
		if( StringUtils.isBlank(list) ||StringUtils.isBlank(callbackurl)){
			throw new HandlerException(40, "缺少必选参数");
		}
		
		String result="";
		List<MobileBean> mbs=new ArrayList<MobileBean>();
		List<JSONObject> arr=null;
		CallbackBean cb=null;
		try {
			arr=(List<JSONObject>) JSONArray.parse(list);
			cb=JSON.parseObject(callbackurl,CallbackBean.class);
			if(StringUtils.isBlank(cb.getApp_key())||StringUtils.isBlank(cb.getApp_url())||StringUtils.isBlank(cb.getMethod())){
				return "callbackurl有误:"+callbackurl;
			}
			MobileBean mb=null;
			for (JSONObject i:arr) {
				mb=JSON.parseObject(i.toJSONString(),MobileBean.class); 
				mb.setAppkey(cb.getApp_key());
				mb.setAppurl(cb.getApp_url());
				mb.setMethod(cb.getMethod());
				mbs.add(mb);
			}
		} catch (Exception e) {
			log.info("数据解析错误，请查看参数");
		}
		if(mbs.size()<=0){
			return "请求成功，未收到数据";
		}
		if(mbs.size()>0){
			result="请求成功，接收 "+mbs.size()+" 条数据！";
		}
		//存放数据
		httpDataContainer.put2MobileCard(mbs);
		return result;
	}
	@WebMethod(exclude=true)
	public Sim get(String mobile){
		return simDao.get(mobile);
	}
	@WebMethod(exclude=true)
	public void save(Account account){
		if(account!=null){
			Sim sim = new Sim(account);
			simDao.update(sim);
		}
	}
	
	@Override
	@WebMethod(exclude=true)
	public Object[] getHandlers() {
		return new Object[]{this};
	}

	@WebMethod(exclude=true)
	public void setSimDao(SimDao simDao) {
		this.simDao = simDao;
	}
	@WebMethod(exclude=true)
	public void setHttpDataContainer(HttpDataContainer httpDataContainer) {
		this.httpDataContainer = httpDataContainer;
	}
}
